package com.swx.guard.util;

import com.sun.jna.Platform;
import com.swx.guard.bean.Service;
import com.swx.guard.bean.ServiceStatus;
import com.swx.guard.bean.UpdateConfig;
import com.xj.starter.util.FileMd5Utils;
import com.xj.starter.util.TerminalUtil;
import lombok.SneakyThrows;
import org.apache.commons.io.FileUtils;

import java.io.File;
import java.io.IOException;
import java.text.MessageFormat;
import java.util.ArrayList;
import java.util.List;

import static com.swx.guard.consts.Const.UPDATE_CONFIG_FILE_NAME;

/**
 * @author Ricky
 * @date 2020/12/4
 */
public class ServiceUtil {


    @SneakyThrows
    public static void updateService(Service service) {
        // 检查是否已下载
        String serviceFileName = service.getFileName();
        String localPath = service.getLocalPath();
        String name = service.getName();
        String tempPath = "temp" + File.separator + name;
        File nameDir = new File(tempPath);
        if (!nameDir.exists()) {
            throw new RuntimeException("升级失败-->服务文件不存在");
        }
        File tempServiceFile = new File(tempPath, serviceFileName);
        if (!tempServiceFile.exists()) {
            throw new RuntimeException("升级失败-->服务文件不存在");
        }

        // 读取临时版本信息
        File tempVersionFile = new File(tempPath, UPDATE_CONFIG_FILE_NAME);
        if (!tempVersionFile.exists()) {
            throw new RuntimeException("升级失败-->版本文件不存在");
        }
        UpdateConfig tempUpdateConfig = PropertiesUtil.getUpdateConfig(tempVersionFile, UpdateConfig.class);


        // 检查临时文件md5
        String fileMd5String = FileMd5Utils.getFileMd5String(tempServiceFile);
        if (!fileMd5String.equalsIgnoreCase(tempUpdateConfig.getMd5())) {
            throw new RuntimeException("升级失败-->服务文件不完整");
        }

        // 读取本地版本信息
        File localVersionFile = new File(localPath, UPDATE_CONFIG_FILE_NAME);
        if (localVersionFile.exists()) {
            UpdateConfig localUpdateConfig = PropertiesUtil.getUpdateConfig(localVersionFile, UpdateConfig.class);
            if (tempUpdateConfig.getVersion().equals(localUpdateConfig.getVersion())) {
                throw new RuntimeException("升级失败-->版本相同，无需升级");
            }
        }

        service.setStatus(ServiceStatus.UPDATING);
        // 停止服务
        List<String> pidList = getPidList(serviceFileName);

        for (String pid : pidList) {
            TerminalUtil.exec(MessageFormat.format("kill -9 {0}", pid));
        }

        // 删除本地服务文件
        File localServiceFile = new File(localPath, serviceFileName);
        if (localServiceFile.exists()) {
            localServiceFile.delete();
        }
        // 删除本地版本文件
        if (localVersionFile.exists()) {
            localVersionFile.delete();
        }

        FileUtils.moveFile(tempServiceFile, localServiceFile);
        FileUtils.moveFile(tempVersionFile, localVersionFile);

        service.setStatus(ServiceStatus.STOP);
    }

    public static List<String> getPidList(String fileName) throws IOException, InterruptedException {
        if (Platform.isWindows()) {
            return new ArrayList<>();
        }
        List<String> resList = TerminalUtil.execToList("ps -ef");
        List<String> pidList = new ArrayList<>();
        for (String s : resList) {
            if (s.contains(fileName)) {
                pidList.add(s.substring(9, 14));
            }
        }
        return pidList;
    }
}
